<template>
  <div class="login-page">
    <div class="login-container">
      <h2 class="login-title">用户登录</h2>
      <form @submit.prevent="handleLogin" class="login-form">
        <!-- 选择身份 -->
        <div class="form-group">
          <label for="role">选择身份：</label>
          <select id="role" v-model="role" class="form-control">
            <option value="teacher">管理员</option>
            <option value="student">学生</option>
          </select>
        </div>

        <!-- 用户名输入框 -->
        <div class="form-group">
          <label for="username">用户名：</label>
          <input
              type="text"
              id="username"
              v-model="username"
              class="form-control"
              placeholder="请输入用户名"
          />
        </div>

        <!-- 密码输入框 -->
        <div class="form-group">
          <label for="password">密码：</label>
          <input
              type="password"
              id="password"
              v-model="password"
              class="form-control"
              placeholder="请输入密码"
          />
        </div>

        <!-- 邮箱输入框 -->
        <div class="form-group">
          <label for="email">邮箱（选填）：</label>
          <input
              type="email"
              id="email"
              v-model="email"
              class="form-control"
              placeholder="请输入邮箱"
          />
        </div>

        <!-- 按钮组 -->
        <div class="button-group">
          <button
              type="submit"
              class="btn btn-primary"
              :disabled="submitting"
          >
            登录
          </button>
          <button
              type="button"
              class="btn btn-secondary"
              @click="handleRegister"
          >
            注册
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import axios from 'axios'; // 导入 Axios 发送 HTTP 请求

export default {
  name: 'LogIn',
  data() {
    return {
      role: '',
      username: '',
      password: '',
      submitting: false, // 用于控制登录按钮是否可点击，避免重复提交
    };
  },
  methods: {
    // 登录操作
    async handleLogin() {
      try {
        const requestData = {
          role: this.role,
          username: this.username,
          password: this.password,
          email: this.email
        };
        console.log('请求数据:', requestData);

        const response = await axios.post("http://39.105.217.183:8000/login", requestData);

        if (response.data.status === "success") {
          this.$store.dispatch("setUser", response.data);
          localStorage.setItem("user", JSON.stringify(response.data)); // 保存到 localStorage
          alert("登录成功");
          if (this.role === 'teacher') {
              this.$router.push('/teacher');
            } else if (this.role === 'student') {
              this.$router.push('/student');
            }
        } else {
          alert("登录失败：" + response.data.message);
        }
      } catch (error) {
        console.error("登录失败:", error);
        alert("登录失败，请稍后重试");
      }
    },
    // 注册操作
    async handleRegister() {
      if (this.validateForm()) {
        if (!this.validatePassword()) {
          alert('密码必须包含至少8个字符，且包括字母、数字和特殊字符');
          return;
        }
        try {
          const response = await axios.post('http://39.105.217.183:8000/register', {
            username: this.username,
            password: this.password,
            email: this.email, // 确保前端表单中有邮箱字段
          });
          if (response.data.status === 'success') {
            alert('注册成功，请重新登录');
            this.resetForm();
            this.$router.push('/login');
          } else {
            alert('注册失败：' + response.data.message);
          }
        } catch (error) {
          console.error('注册错误:', error);
          alert('注册失败，请稍后重试');
        }
      }
    },
    // 验证表单内容
    validateForm() {
      if (!this.role) {
        alert('请选择身份');
        return false;
      }
      if (!this.username) {
        alert('请输入用户名');
        return false;
      }
      if (!this.password) {
        alert('请输入密码');
        return false;
      }
      return true;
    },
    // 验证密码复杂性
    validatePassword() {
      const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[^\w])\S{8,}$/;
      return passwordRegex.test(this.password);
    },
    // 重置表单
    resetForm() {
      this.role = '';
      this.username = '';
      this.password = '';
      this.email = ''; // 清空邮箱字段
    },
  },
};
</script>

<style scoped>
/* 登录页面整体布局 */
.login-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  font-family: 'Open Sans', Arial, sans-serif;
}

/* 登录框容器 */
.login-container {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  padding: 40px 30px;
  width: 80%;
  max-width: 600px;
  text-align: center;
}

@media (min-width: 1024px) {
  .login-container {
    max-width: 500px;
    width: 50%;
  }
}

/* 标题和副标题 */
.login-title {
  font-size: 2rem;
  color: #2563eb;
  margin-bottom: 10px;
  font-weight: 700;
}

.login-subtitle {
  font-size: 1rem;
  color: #6b7280;
  margin-bottom: 30px;
}

/* 表单样式 */
.login-form .form-group {
  margin-bottom: 20px;
  text-align: left;
}

.login-form .form-group label {
  display: block;
  font-size: 0.9rem;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.login-form .form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s;
}

.login-form .form-group input:focus {
  border-color: #2563eb;
  outline: none;
  box-shadow: 0 0 4px rgba(37, 99, 235, 0.4);
}

/* 按钮样式 */
.btn {
  display: block;
  width: 100%;
  padding: 12px;
  background-color: #2563eb;
  color: #ffffff;
  font-size: 1rem;
  font-weight: 600;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.2s;
}

.btn:hover {
  background-color: #1e40af;
  transform: scale(1.02);
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 页脚链接 */
.login-footer {
  font-size: 0.9rem;
  color: #6b7280;
  margin-top: 20px;
}

.login-footer a {
  color: #2563eb;
  font-weight: 600;
  text-decoration: none;
}

.login-footer a:hover {
  text-decoration: underline;
}
</style>